#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"

#include "request.pb.h"
#include <iostream>
#include <unordered_map>

const std::string listenAddr = "0.0.0.0";

class Server
{
    using MessagePtr = std::shared_ptr<google::protobuf::Message>;
    using TranslateRequestPtr = std::shared_ptr<request::TranslateRequest>;
    using AddRequestPtr = std::shared_ptr<request::AddRequest>;
public:
    Server(uint16_t port)
        : server_(&baseloop_, muduo::net::InetAddress(listenAddr, port), 
            "Server", muduo::net::TcpServer::Option::kReusePort)
        , dispatcher_(std::bind(&Server::onUnknownMessage, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
        , codec_(std::bind(&ProtobufDispatcher::onProtobufMessage, &dispatcher_, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        dispatcher_.registerMessageCallback<request::TranslateRequest>(std::bind(&Server::onTranslate, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        dispatcher_.registerMessageCallback<request::AddRequest>(std::bind(&Server::onAdd, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));  

        server_.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &codec_,
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        server_.setConnectionCallback(std::bind(&Server::onConnection, this, std::placeholders::_1));
    }

    void start()
    {
        server_.start();
        baseloop_.loop();
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected() == true) 
            LOG_INFO << "The new connection is successfully established!\n";
        else
            LOG_INFO << "The new connection is closed\n";
    }

    std::string translate(const std::string& data)
    {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"apple", "苹果"},
            {"eat", "吃"},
            {"happy", "快乐"}
        };
        auto it = dict_map.find(data);
        if(it == dict_map.end()) return std::move("听不懂，退朝！\n");
        return it->second;
    }

    void onTranslate(const muduo::net::TcpConnectionPtr& conn,
                    const TranslateRequestPtr& message, muduo::Timestamp)
    {
        // 1. 提取message有效信息
        std::string req_msg = message->msg();
        // 2. 翻译
        std::string rsep_msg = translate(req_msg);
        // 3. 组织proto响应
        request::TranslateResponse resp;
        resp.set_msg(rsep_msg);
        // 4. 发送响应
        codec_.send(conn, resp);
    }

    void onAdd(const muduo::net::TcpConnectionPtr& conn,
                const AddRequestPtr& message, muduo::Timestamp)
    {
        int num1 = message->num1();
        int num2 = message->num2();
        int result = num1 + num2;
        request::AddResponse resp;
        resp.set_result(result);
        codec_.send(conn, resp);
    }   

    void onUnknownMessage(const muduo::net::TcpConnectionPtr& conn,
                        const MessagePtr& message,
                        muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

private:
    muduo::net::EventLoop baseloop_;
    muduo::net::TcpServer server_;
    ProtobufDispatcher dispatcher_;    // 请求分发器对象, 向其中注册请求处理函数
    ProtobufCodec codec_;              // 协议处理器, 针对收到的请求数据进行protobuf协议处理
};

int main()
{
    Server server(8888);
    server.start();
    return 0;
}